package cn.youframe.frame.security;

import cn.youframe.frame.base.YFBase;
import cn.youframe.frame.beans.Menber;
import cn.youframe.frame.util.PassWord;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.Set;

/**
 * User: Administrator
 * DateTime: 12-7-24: 下午2:45
 */
public class UserDetailServiceImpl implements UserDetailsService,YFBase{
    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("username is :"+username);
        Menber menber=userDao.findByName(username);
        int online=userDao.userOnline(username);
        if(menber == null) {
            throw new UsernameNotFoundException(username);
        }
        String pwd= PassWord.decode(menber.getPassword());
        boolean enables = false;
        if(menber.getEnable().equals("0")){
            enables=true;
        }
        boolean accountNonExpired = false;
        if(menber.getExpiredDays()>0){
            accountNonExpired=true;
        }
        boolean credentialsNonExpired = true;
        if(menber.getPwdUpdateDays()>90){
            credentialsNonExpired=false;
        }
        boolean accountNonLocked = (online>0)?false:true;
        User userdetail = new User(menber.getAccount(),pwd, enables, accountNonExpired, credentialsNonExpired, accountNonLocked,obtionGrantedAuthorities());
        return userdetail;
    }
    //取得用户的权限
    private Set<GrantedAuthority> obtionGrantedAuthorities() {
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
        authSet.add(new SimpleGrantedAuthority("user"));
        return authSet;
    }
}
